<?php
//系统转换
class IndexAction extends Action
{
	private $install_lock;
	private function getRealPath()
	{
		return FANWE_ROOT;
	}

	public function __construct()
	{
		import("ORG.Io.Dir");
		parent::__construct();
		$this->install_lock = FANWE_ROOT."public/install.lock";
	}

    public function index()
	{
		clear_cache();
		if(file_exists($this->install_lock))
		{
			$this->assign("jumpUrl",__ROOT__."/../");
			$this->error("系统已经升级");
		}
		else
		{
			$note = file_get_contents(FANWE_ROOT.'update/update.txt');
			$this->assign("note",nl2br($note));
			$this->display();
		}
    }

	public function msg($msg)
    {
		$this->assign("msg",$msg);
		$this->display('msg');
		exit;
    }
	
	public function check()
	{
		$olddb_config = @include OLD_ROOT_PATH.'public/db.global.php';
		$config_global = @file_get_contents(OLD_ROOT_PATH.'public/config.global.php');
		if(!$olddb_config || empty($config_global))
			$this->msg('未找到原分享网站配置文件，请参照升级说明.txt进行相关设置');
		
		$status = 1;
		$check_dirs = array();
		
		$dirs = C("DIRS_CHECK");
    	foreach($dirs as $item)
    	{
			$item_path = $item['path'];
			$file['name'] = $item_path;
			$file['ask'] = '可读写';
			
			if($item['type'] == 'dir')
			{
				if(file_exists(FANWE_ROOT.$item_path))
				{
					if(!dirWriteable(FANWE_ROOT.$item_path))
					{
						$file['status'] = 0;
						$file['msg'] = '只读';
						$status = 0;
					}
					else
					{
						$file['status'] = 1;
						$file['msg'] = '可读写';
					}
				}
				else
				{
					$file['status'] = 0;
					$file['msg'] = '没有目录';
					$status = 0;
				}
			}
			else
			{
				if(file_exists(FANWE_ROOT.$item_path))
				{
					if(is_writable(FANWE_ROOT.$item_path))
					{
						$file['status'] = 1;
						$file['msg'] = '可读写';
					}
					else
					{
						$file['status'] = 0;
						$file['msg'] = '只读';
						$status = 0;
					}
				}
				else
				{
					$file['status'] = 0;
					$file['msg'] = '没有文件';
					$status = 0;
				}
			}
			$check_dirs[] = $file;
    	}
		
		$this->assign("status",$status);
		$this->assign("check_dirs",$check_dirs);
		$this->display();
	}

    public function update()
    {
		$olddb_config = @include OLD_ROOT_PATH.'public/db.global.php';
		$config_global = @file_get_contents(OLD_ROOT_PATH.'public/config.global.php');
		if(!$olddb_config || empty($config_global))
			$this->msg('未找到原分享网站配置文件，请参照升级说明.txt进行相关设置');
		
		$this->assign("olddb_config",$olddb_config);
		$this->display();
    }

	public function doupdate()
	{
		$olddb_config = @include OLD_ROOT_PATH.'public/db.global.php';
		$config_global = @file_get_contents(OLD_ROOT_PATH.'public/config.global.php');
		if(!$olddb_config || empty($config_global))
			$this->msg('未找到原分享网站配置文件，请参照升级说明.txt进行相关设置');

        $db_prefix = trim($_REQUEST['db_prefix']);
		if(empty($db_prefix))
			$this->msg('请设置新分享表前缀');
			
		if($db_prefix == $olddb_config['DB_PREFIX'])
			$this->msg('新分享表前缀不能跟原分享表前缀('.$olddb_config['DB_PREFIX'].')相同');
		
		$db_config = $olddb_config;
		$db_config['DB_PREFIX'] = $db_prefix;
		$db_config_str 	 = 	"<?php\r\n";
		$db_config_str	.=	"return array(\r\n";
		foreach($db_config as $key=>$v)
		{
			$db_config_str.="'".$key."'=>'".$v."',\r\n";
		}
		$db_config_str.=");\r\n";
		$db_config_str.="?>";
		@file_put_contents(FANWE_ROOT."public/db.global.php",$db_config_str);
		@file_put_contents(FANWE_ROOT.'public/config.global.php', $config_global);
		$this->redirect('Index/runsql');
	}
	
	public function runsql()
	{
		@set_time_limit(3600);
        if(function_exists('ini_set'))
            ini_set('max_execution_time',3600);
		
		$db_config = @include FANWE_ROOT."public/db.global.php";
		$index = isset($_REQUEST['index']) ? (int)$_REQUEST['index'] : 0;
		$sql_file = FANWE_ROOT."update/sqls/install_".$index.".sql";
		$this->display();

		flush();
		ob_flush();

		showjsmessage('',-1);

		if(file_exists($sql_file))
		{
			showjsmessage("正在执行SQL install_".$index.".sql",2);
			if($this->restore($sql_file,$db_config))
			{
				$index++;
				showjsmessage(U('Index/runsql',array('index'=>$index)),3);
			}	
			else
				showjsmessage("执行SQL install_".$index.".sql 发生错误",1);
		}
		else
		{
			$host = $db_config['DB_HOST'];
			if(!empty($db_config['DB_PORT']))
				$host = $db_config['DB_HOST'].':'.$db_config['DB_PORT'];

			Vendor("mysql");
			$db = new mysqldb(array('dbhost'=>$host,'dbuser'=>$db_config['DB_USER'],'dbpwd'=>$db_config['DB_PWD'],'dbname'=>$db_config['DB_NAME'],'dbcharset'=>'utf8','pconnect'=>0));
			
			$db->query('DROP TRIGGER IF EXISTS `Archive`','SILENT');
			$archive_sql = 'CREATE TRIGGER `Archive` BEFORE UPDATE ON `%DB_PREFIX%apns_devices`
				 FOR EACH ROW INSERT INTO `%DB_PREFIX%apns_device_history` VALUES (
					NULL,
					OLD.`clientid`,
					OLD.`appname`,
					OLD.`appversion`,
					OLD.`deviceuid`,
					OLD.`devicetoken`,
					OLD.`devicename`,
					OLD.`devicemodel`,
					OLD.`deviceversion`,
					OLD.`pushbadge`,
					OLD.`pushalert`,
					OLD.`pushsound`,
					OLD.`development`,
					OLD.`status`,
					NOW()
				)';
			$db->query(str_replace("%DB_PREFIX%",$db_config['DB_PREFIX'],$archive_sql),'SILENT');
            @file_put_contents($this->install_lock,"");
			vendor('common');         
            include_once fimport('class/cache');
            Cache::getInstance()->updateCache();
			$this->redirect('Index/updatetable');
		}
	}

	public function updatetable()
	{
		@set_time_limit(0);
        if(function_exists('ini_set'))
            ini_set('max_execution_time',0);
			
		define('SYS_DEBUG',true);

		$tables = @include FANWE_ROOT."update/Common/tables.php";
		$olddb_config = @include OLD_ROOT_PATH.'public/db.global.php';
		
		if(!$tables || !$olddb_config)
			$this->msg('获取配置文件发生错误');

		$tableIndex = isset($_REQUEST['table']) ? (int)$_REQUEST['table'] : 0;
		$tableIndex = max($tableIndex,0);
		$begin = isset($_REQUEST['begin']) ? (int)$_REQUEST['begin'] : 0;
		$begin = max($begin,0);
		$this->display();

		ob_start();
		ob_end_flush(); 
		ob_implicit_flush(1);
		
		if($tableIndex < count($tables))
		{
			$tableTaget = $tables[$tableIndex]['name'];
			showjsmessage("正在初始化".$tableTaget."转换表数据，请稍候...",2);

			global $newDB,$oldDB;
			$old_host = $olddb_config['DB_HOST'];
			if(!empty($olddb_config['DB_PORT']))
				$old_host = $olddb_config['DB_HOST'].':'.$olddb_config['DB_PORT'];
				
			vendor('common');
			vendor("mysql");
			
			@file_put_contents(FANWE_ROOT.'public/update_log.txt',$tableTaget."\n".$tableIndex."\n".$begin);
			
			$oldDB = new mysqldb(array('dbhost'=>$old_host,'dbuser'=>$olddb_config['DB_USER'],'dbpwd'=>$olddb_config['DB_PWD'],'dbname'=>$olddb_config['DB_NAME'],'tablepre'=>$olddb_config['DB_PREFIX'],'dbcharset'=>'utf8','pconnect'=>0));
			
			if(!$oldDB)
				$this->msg('数据库链接错误');
			
			if($tables[$tableIndex]['type'] < 2)
			{
				$get_table = $oldDB->resultFirst("SHOW TABLES LIKE '".$oldDB->tableName($tableTaget)."'");
				if(empty($get_table))
				{
					showjsmessage(U('Index/updatetable',array('table'=>$tableIndex + 1)),5);
					exit;
				}
			}
			
			$limit = 100;
			if($tables[$tableIndex]['type'] == 0)
				@include FANWE_ROOT.'update/Common/table/current.table.php';
			else
				@include FANWE_ROOT.'update/Common/table/'.$tableTaget.'.table.php';
		}
		else
		{
			$this->redirect('Index/updateok');
			exit;
		}
	}
	
	public function updateok()
	{
		$this->display();
	}
	
   /**
     * 执行SQL脚本文件
     *
     * @param array $filelist
     * @return string
     */
    private function restore($file,$db_config)
    {
		@set_time_limit(0);
		@ini_set('memory_limit', '128M');

		$host = $db_config['DB_HOST'];
        if(!empty($db_config['DB_PORT']))
            $host = $db_config['DB_HOST'].':'.$db_config['DB_PORT'];

		Vendor("mysql");
		$db = new mysqldb(array('dbhost'=>$host,'dbuser'=>$db_config['DB_USER'],'dbpwd'=>$db_config['DB_PWD'],'dbname'=>$db_config['DB_NAME'],'dbcharset'=>'utf8','pconnect'=>0));
		$sql = file_get_contents($file);
		$sql = $this->remove_comment($sql);
		$sql = trim($sql);

		$bln = true;

		$tables = array();

		$sql = str_replace("\r", '', $sql);
		$segmentSql = explode(";\n", $sql);
		$table = "";

		foreach($segmentSql as $k=>$itemSql)
		{
			$itemSql = trim(str_replace("%DB_PREFIX%",$db_config['DB_PREFIX'],$itemSql));

			if(strtoupper(substr($itemSql, 0, 12)) == 'CREATE TABLE')
			{
				$table = preg_replace("/CREATE TABLE (?:IF NOT EXISTS |)(?:`|)([a-z0-9_]+)(?:`|).*/is", "\\1", $itemSql);

				if(!in_array($table,$tables))
					$tables[] = $table;

				if($db->query($itemSql) === false)
				{
					$bln = false;
					showjsmessage("建立数据表 ".$table." ... 失败",1);
					break;
				}
				else
				{
					showjsmessage("建立数据表 ".$table." ... 成功");
				}
			}
			else
			{
				if($db->query($itemSql) === false)
				{
					$bln = false;
					showjsmessage("添加数据表 ".$table." ... 数据失败",1);
					break;
				}
			}
		}

		return $bln;
    }



    /**
     * 过滤SQL查询串中的注释。该方法只过滤SQL文件中独占一行或一块的那些注释。
     *
     * @access  public
     * @param   string      $sql        SQL查询串
     * @return  string      返回已过滤掉注释的SQL查询串。
     */
    private function remove_comment($sql)
    {
        /* 删除SQL行注释，行注释不匹配换行符 */
        $sql = preg_replace('/^\s*(?:--|#).*/m', '', $sql);

        /* 删除SQL块注释，匹配换行符，且为非贪婪匹配 */
        //$sql = preg_replace('/^\s*\/\*(?:.|\n)*\*\//m', '', $sql);
        $sql = preg_replace('/^\s*\/\*.*?\*\//ms', '', $sql);

        return $sql;
    }
}
?>